package server;

import javax.xml.ws.Endpoint;

import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.ws.addressing.WSAddressingFeature;

import server.implementation.TimeTableImpl;

public class Server implements Runnable
{
	/**
	 * 1 - running
	 * 0 - stopped
	 */
	private int state = 1;
	
	public Server(String port) throws Exception 
	{
		System.out.println("Starting Server");
		
		TimeTableImpl implementor =  new TimeTableImpl();
		EndpointImpl ep = (EndpointImpl) Endpoint.create(implementor);
		ep.getFeatures().add(new WSAddressingFeature());
		
		if(port.equals(""))
			port = "9000";
		
		ep.publish("http://localhost:" + port + "/timetable");

		System.out.println("Server ready...");
	}
	
	public int getState()
	{
		return state;
	}

	public void setState(int state)
	{
		this.state = state;
	}

	public synchronized void run()
	{
		while(state == 1)
		{
			try
			{
				Thread.sleep(1000);
			} 
			catch (InterruptedException e)
			{
				System.out.println("Server exiting");
				e.printStackTrace();
			}
		}
		
		if(state == 0)
		{
			System.out.println("Server exiting");
		}
		else
		{
			System.out.println("Server state error: " + state);
		}
		
		closeEndpoints();
	}

	public void closeEndpoints()
	{
		// TODO !!!
//		for (int i = 0; i < endpoints.size(); i++)
//		{
//			endpoints.get(i).stop();
//		}
	}
}
